# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
import os
import pymongo


class MongoPipeline(object):
    def __init__(self, mongo_uri, mongo_db):
        self.mongo_uri = mongo_uri
        self.mongo_db = mongo_db

    @classmethod
    def from_crawler(cls, crawler):
        return cls(
            mongo_uri=crawler.settings.get('MONGODB_URI'),
            mongo_db=crawler.settings.get('MONGODB_DATABASE')
        )

    def open_spider(self, spider):
        self.client = pymongo.MongoClient(self.mongo_uri)
        self.db = self.client[self.mongo_db]

    def close_spider(self, spider):
        self.client.close()

    def process_item(self, item, spider):
        collection_name = item['titlename']
        self.db[collection_name].insert_one(dict(item))
        return item


class NoveldownloadPipeline(object):
    def process_item(self, item, spider):
        curPath = 'F:\\笔趣阁小说'
        tempPath = str(item['titlename'])
        targetPath = curPath + os.path.sep + tempPath
        if not os.path.exists(targetPath):
            os.makedirs(targetPath)
        filename_path = 'F:\\笔趣阁小说' + os.path.sep + str(item['titlename']) + os.path.sep + str(
            item['chaptername']) + '.txt'
        with open(filename_path, 'w', encoding='utf-8') as f:
            f.write(item['text'] + "\n")

        return item
